//
//  CofirmOrder_Vc.swift
//  Pods
//
//  Created by eme on 2017/4/5.
//
//

/*
 owner:cy
 update:2017年04月05日09:10:01
 info: 确认订单界面
 */
import RxSwift
import UtilCore
import RickonCore
import Presentr
import BrandonCore

let BuyErrorAlert_Height:CGFloat = 410

class CofirmOrder_Vc: Base_Vc {
    
    /****************************Storyboard UI设置区域****************************/
    @IBOutlet weak var cofirmOrder_Tv: UITableView!
    
    @IBOutlet weak var finaltotalprice_Lb: UILabel!
    
    /// 如果已经选择了地址或包含默认地址则需要显示该view
    @IBOutlet weak var addressContent_V: UIView!
    
    @IBOutlet weak var recipients_Lb: UILabel!
    
    @IBOutlet weak var address_Lb: UILabel!
    
    @IBOutlet weak var cellphone_Lb: UILabel!
    
    @IBOutlet weak var submit_Btn: UIButton!
    
    @IBOutlet var pickAddress_Tap: UITapGestureRecognizer!
    /*----------------------------   自定义属性区域    ----------------------------*/
    var manageVm:CofirmOrder_Vm?
    var addid :String?
    var orderFormModel :OrderFormModel?{
        didSet{
            self.firstUpdateOrderFormTvData()
        }
    }
    var ordersumamount:String?
    ///选中的优惠券
    var voucherModel:VouchersModel?
    var addressModel:AddressModel?{
        didSet{
            if let model = self.addressModel, model.addid.characters.count > 0{
                self.addressContent_V.isHidden = false
                self.address_Lb.text = "\(model.province)\(model.city)\(model.area)\(model.adress)"
                self.cellphone_Lb.text = model.cellphone
                self.recipients_Lb.text = model.recipients
                self.addid = model.addid
            }else{
                self.addressContent_V.isHidden = true
            }
            
        }
    }
    /// 是否开发票
    var invoiceInf:String = "0"{
        didSet{
            self.updateOrderFormTvData()
        }
    }
    var presenter: Presentr?
    var cofirmParam:(osCarts:NSString,iscart:String)?
    var ismix:String = "0"
    /****************************Storyboard 绑定方法区域****************************/
    
    
    
    /**************************** 以下是方法区域 ****************************/
    override func viewDidLoad() {
        super.viewDidLoad()
        
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        
    }
    
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
    }
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        
    }
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        if let identifier = segue.identifier { // 检查是否 nil
            switch identifier {
            case "Invoice_Vc":
                if let vc = segue.destination as? Invoice_Vc { // 如果非 nil，
                    vc.radioState = sender as? String
                    vc.didUpdateState = {[unowned self] state in
                        self.invoiceInf = state
                    }
                }
            case "GwqList_Vc":
                if let vc = segue.destination as? GwqList_Vc { // 如果非 nil，
                    vc.myvoucherlist = self.orderFormModel?.myvoucherlist
                    vc.voucherItem = self.voucherModel
                    vc.didUpdateState = {[unowned self] item in
                        self.voucherModel = item
                        self.updateOrderFormTvData()
                    }
                }
            default: break
            }
        }
    }
    /**
     界面基础设置
     */
    override func setupUI() {
        /**
         *  自定义 导航栏左侧 返回按钮
         */
        self.customLeftBarButtonItem()
        self.tabBarController?.tabBar.isHidden = true
        let width = ModalSize.custom(size: Float(self.view.frame.width) - 40)
        let height = ModalSize.custom(size: Float(BuyErrorAlert_Height))
        
        let center = ModalCenterPosition.customOrigin(origin: CGPoint(x: 20, y: self.view.center.y - BuyErrorAlert_Height/2))
        
        let customType = PresentationType.custom(width: width, height: height, center: center)
        let customPresenter = Presentr(presentationType: customType)
        customPresenter.transitionType = .coverVertical
        customPresenter.roundCorners = false
        self.presenter = customPresenter
        ///隐藏滑动条
        self.cofirmOrder_Tv.showsVerticalScrollIndicator = false
        self.title = "确认订单"
    }
    /**
     app 主题 设置
     */
    override func setViewTheme(){
        
    }
    /**
     绑定到viewmodel 设置
     */
    override func bindToViewModel(){
        let refreshTriger = Observable.just().filter{ _ in
            self.cofirmParam != nil
            }.map{ _ in  self.cofirmParam! }
        self.manageVm = CofirmOrder_Vm(refreshTriger: refreshTriger)
        
        self.manageVm?.productItem
            .subscribe(onNext: {[unowned self] (item) in
                if item.myvoucherlist.count > 0 {
                    self.voucherModel = item.myvoucherlist[0]
                }
                self.orderFormModel = item
            })
            .disposed(by: disposeBag)
        self.submit_Btn
            .rx.tap
            .subscribe(onNext: { [unowned self] ( _ ) in
                if let model = self.orderFormModel{
                    if let addressModel = self.addressModel, addressModel.addid.characters.count > 0{
                        let item = self.getSubmitParam(effective:model.effective)
                        if item.isOk{
                            self.manageVm?.createOrderSubject.onNext(item.param as Dictionary<String, AnyObject>)
                        }else{
                            showMsg(item.msg)
                        }
                    }else{
                        showMsg(100041004)
                    }
                }
            })
            .disposed(by: disposeBag)
        
        
        self.manageVm?.createOrderSuccess
            .subscribe(onNext: { [unowned self] ( createOrder) in
                switch createOrder.status{
                case "0":
                    /// 获取进货单数量
                    _ = "orderformbadge".openURL()
                    _ = "pay".openURL(["payid":createOrder.payid,"ordersumamount":createOrder.orderSumAmount.getPriceStr(),"ordertype":"OS"])
                case "1","2":
                    self.sowErrorAlertVc(createModel: createOrder)
                default:
                    showMsg("不能购买")
                }
            })
            .disposed(by: disposeBag)
        self.manageVm?
            .loading
            .asObservable()
            .bindTo(self.view.rx_loading)
            .disposed(by: disposeBag)
        self.manageVm?
            .error
            .bindTo(self.view.rx_error)
            .disposed(by: disposeBag)
        self.pickAddress_Tap
            .rx.event
            .subscribe(onNext: { [unowned self] ( _ ) in
                if self.addressModel == nil {
                    let addressListVc = AryaCore.storyboard.instantiateViewController(withIdentifier: "AddNewAddress_Vc") as! AddNewAddress_Vc
                    addressListVc.didSelectedAddressModel = { model in
                        self.addressModel = model
                        self.addid = model.addid
                    }
                    self.navigationController?.pushViewController(addressListVc, animated: true)
                }else{
                    let addressListVc = AryaCore.storyboard.instantiateViewController(withIdentifier: "AddressList_Vc") as! AddressList_Vc
                    addressListVc.didSelectedAddressModel = { model in
                        if let model = model {
                            self.addid = model.addid
                        }
                        self.addressModel = model
                    }
                    addressListVc.addressModel = self.addressModel
                    addressListVc.addid = self.addid
                    self.navigationController?.pushViewController(addressListVc, animated: true)
                }
            })
            .disposed(by: disposeBag)
    }
}
extension CofirmOrder_Vc{
    func sowErrorAlertVc(createModel:CreateOrderModel) -> Void {
        let errorAlertVc:BuyErrorAlert_Vc = AryaCore.storyboard.instantiateViewController(withIdentifier: "BuyErrorAlert_Vc") as! BuyErrorAlert_Vc
        errorAlertVc.createOrder = createModel
        errorAlertVc.didSubmit_Closure = { param in
            if let addressModel = self.addressModel, addressModel.addid.characters.count > 0{
                self.manageVm?.createOrderSubject.onNext(self.getSubmitParam(pds:param) as Dictionary<String, AnyObject>)
            }else{
                ///未选择收货地址提交订单
                showMsg(100041004)
            }
        }
        self.customPresentViewController(self.presenter!, viewController: errorAlertVc, animated: true, completion: nil)
    }
    /// 创建订单参数
    func getSubmitParam(effective:[OrderProductModel]) -> (isOk:Bool,msg:String,param:[String:String]){
        var sparmArr:[String:String] = [:]
        sparmArr["addid"] = self.addressModel!.addid
        sparmArr["invoiceflag"] = self.invoiceInf
        ///是否混批 默认0 表示不混批
        sparmArr["ismix"] = self.ismix
        if let voucherModel = self.voucherModel {
            sparmArr["paycouponid"] = voucherModel.uvid
        }
        var spds:[[String:String]] = []
        var isOk = true
        var errorMsg = ""
        for order in effective{
            for item in order.array {
                for subItem in item.array {
                    var subRelItem :[String:String] = [:]
                    subRelItem["skuid"] = "\(subItem.skuid)"
                    subRelItem["pdid"] = "\(subItem.pdid)"
                    subRelItem["editnum"] = "\(subItem.skunum)"
                    subRelItem["pdcode"] = "\(order.message)"
                    subRelItem["psvalue"] = "\(subItem.cartid)"
                    spds.append(subRelItem)
                    if order.message.characters.count > 100 {
                        isOk = false
                        errorMsg = AppConfig.alert[100041003]?.msgtitle ?? ""
                        break
                    }
                }
            }
        }
        sparmArr["pds"] = JSONHelper.parseToJson(spds as AnyObject) as String
        return (isOk,errorMsg,sparmArr)
    }
    func getSubmitParam( pds:String) -> [String:String] {
        var sparmArr:[String:String] = [:]
        sparmArr["addid"] = self.addressModel!.addid
        sparmArr["invoiceflag"] = self.invoiceInf
        ///是否混批 默认0 表示不混批
        sparmArr["ismix"] = self.ismix
        sparmArr["pds"] = pds
        if let voucherModel = self.voucherModel {
            sparmArr["paycouponid"] = voucherModel.uvid
        }
        return sparmArr
    }
    ///第一进入 然后初始化数据
    func firstUpdateOrderFormTvData() -> Void {
        if let model = self.orderFormModel{
            if let voucherModel = self.voucherModel {
                self.finaltotalprice_Lb.text = "合计:\((model.finaltotalprice - voucherModel.vcost).getPriceStr())元"
                self.ordersumamount = (model.finaltotalprice - voucherModel.vcost).getPriceStr()
            }else{
                self.finaltotalprice_Lb.text = "合计:\(model.finaltotalprice.getPriceStr())元"
                self.ordersumamount = model.finaltotalprice.getPriceStr()
            }
            /// 如果addressModel 为nil 则 说明是第一次初始化界面， 否则表示已经选择了地址然后每次更新界面的是否不覆盖addressModel
            if model.defaultaddress.addid.characters.count > 0 {
                self.addressModel = model.defaultaddress
            }
        }else{
            self.addressContent_V.isHidden = true
            self.finaltotalprice_Lb.text = "合计:0.00元"
            self.ordersumamount = 0.00.getPriceStr()
            
        }
        self.cofirmOrder_Tv.reloadData()
    }
    func updateOrderFormTvData() -> Void {
        if let model = self.orderFormModel{
            if let voucherModel = self.voucherModel {
                self.finaltotalprice_Lb.text = "合计:\((model.finaltotalprice - voucherModel.vcost).getPriceStr())元"
                self.ordersumamount = (model.finaltotalprice - voucherModel.vcost).getPriceStr()
            }else{
                self.finaltotalprice_Lb.text = "合计:\(model.finaltotalprice.getPriceStr())元"
                self.ordersumamount = model.finaltotalprice.getPriceStr()
            }
        }else{
            self.addressContent_V.isHidden = true
            self.finaltotalprice_Lb.text = "合计:0.00元"
            self.ordersumamount = 0.00.getPriceStr()
            
        }
        self.cofirmOrder_Tv.reloadData()
    }
}
// MARK: UITableViewDelegate
extension CofirmOrder_Vc :UITableViewDataSource{
    func numberOfSections(in tableView: UITableView) -> Int {
        if let model = self.orderFormModel {
            /// 如果商品为0 则什么都不显示
            if model.effective.count == 0 {
                return 0
            }
            ///  邮费 和 下面的 商品总金额 显示  issueaninvoice 是否开发票,0否,1是
            // 这块也有可能包含 是否使用优惠券
            if model.issueaninvoice == "1" || model.myvoucherlist.count > 0 {
                return model.effective.count + 1 + 1
            }else{
                //不包含是否开发票 并且没有优惠券
                return model.effective.count + 1
            }
            
        }else{
            return 0
        }
    }
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int{
        let model = self.orderFormModel!
        if section < model.effective.count {
            return model.effective[section].array.count
        }else if section == model.effective.count{
            ///  邮费 和 下面的 商品总金额 显示  issueaninvoice 是否开发票,0否,1是
            // 这块也有可能包含 是否使用优惠券
            if model.issueaninvoice == "1" && model.myvoucherlist.count > 0{
                /// 如果同时包含发票信息和 优惠券的话 则两个cell 否则 一个cell
                return 2
            }else{
                return 1
            }
        }else{
            /// 显示总计
            return 1
        }
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell{
        let model = self.orderFormModel!
        if model.issueaninvoice == "1" || model.myvoucherlist.count > 0 {
            /// 显示发票选项
            if indexPath.section == model.effective.count {
                let cell = tableView.dequeueReusableCell(withIdentifier: "CofirmOrder_Bill_TCell", for: indexPath) as! CofirmOrder_Bill_TCell
                /*
                 这块的判断逻辑是
                 1.如果配置显示发票信息，则第一行显示发票信息
                 2.如果返回的包含了 优惠券信息，则第二行显示优惠券
                 3.只包含优惠券，则第一行显示优惠券
                 */
                ///  邮费 和 下面的 商品总金额 显示  issueaninvoice 是否开发票,0否,1是
                // 这块也有可能包含 是否使用优惠券
                if model.issueaninvoice == "1" {
                    if indexPath.row == 0 {
                        cell.invoice_Lb.text = "发票信息"
                        if  invoiceInf == "1" {
                            if let user = AppData.loginedUser {
                                cell.invoice_Desc_Lb.text = user.glShop.spcompany
                            }else{
                                cell.invoice_Desc_Lb.text = ""
                            }
                        }else{
                            cell.invoice_Desc_Lb.text = "不开发票"
                        }
                    }else{
                        /// 这块应该是第二行，显示优惠券，
                        cell.invoice_Lb.text = "优惠券"
                        if let voucher =  self.voucherModel {
                            cell.invoice_Desc_Lb.text = voucher.showTitle
                        }else{
                            cell.invoice_Desc_Lb.text = "不使用优惠券"
                        }
                    }
                }else{
                    /// 这块应该是第二行，显示优惠券，
                    cell.invoice_Lb.text = "优惠券"
                    if let voucher =  self.voucherModel {
                        cell.invoice_Desc_Lb.text = voucher.showTitle
                    }else{
                        cell.invoice_Desc_Lb.text = "不使用优惠券"
                    }
                }
                return cell
            }else if indexPath.section == model.effective.count + 1 {
                /// 显示商品 金额总计
                let cell = tableView.dequeueReusableCell(withIdentifier: "CofirmOrder_Final_TCell", for: indexPath) as! CofirmOrder_Final_TCell
                cell.item = model
                if let voucherModel = self.voucherModel {
                    ///表示使用了优惠券，总价格需要减去优惠券
                    cell.finalposttag_Lb.text = "-\(voucherModel.vcost.getPriceStr())"
                    cell.finaltotalprice_Lb.text = (model.finaltotalprice - voucherModel.vcost).getPriceStr()
                    self.ordersumamount = (model.finaltotalprice - voucherModel.vcost).getPriceStr()
                    cell.yhq_V.isHidden = false
                }else{
                    /// 表示没有使用优惠券
                    cell.finalposttag_Lb.text = "-\(0.0.getPriceStr())"
                    cell.finaltotalprice_Lb.text = model.finaltotalprice.getPriceStr()
                    self.ordersumamount = model.finaltotalprice.getPriceStr()
                    cell.yhq_V.isHidden = true
                }
                return cell
            }else{
                let cell = tableView.dequeueReusableCell(withIdentifier: "CofirmOrder_TCell", for: indexPath) as! CofirmOrder_TCell
                cell.item = model.effective[indexPath.section].array[indexPath.row]
                return cell
            }
            
        }else{
            //不包含是否开发票
            /// 显示发票选项
            if indexPath.section == model.effective.count {
                /// 显示商品 金额总计
                let cell = tableView.dequeueReusableCell(withIdentifier: "CofirmOrder_Final_TCell", for: indexPath) as! CofirmOrder_Final_TCell
                cell.item = model
                if let voucherModel = self.voucherModel {
                    ///表示使用了优惠券，总价格需要减去优惠券
                    cell.finalposttag_Lb.text = "-\(voucherModel.vcost.getPriceStr())"
                    cell.finaltotalprice_Lb.text = (model.finaltotalprice - voucherModel.vcost).getPriceStr()
                    self.ordersumamount = (model.finaltotalprice - voucherModel.vcost).getPriceStr()
                    cell.yhq_V.isHidden = false
                }else{
                    /// 表示没有使用优惠券
                    cell.finalposttag_Lb.text = "-\(0.0.getPriceStr())"
                    cell.finaltotalprice_Lb.text = model.finaltotalprice.getPriceStr()
                    cell.yhq_V.isHidden = true
                    self.ordersumamount =  model.finaltotalprice.getPriceStr()
                }
                return cell
            }else{
                let cell = tableView.dequeueReusableCell(withIdentifier: "CofirmOrder_TCell", for: indexPath) as! CofirmOrder_TCell
                cell.item = model.effective[indexPath.section].array[indexPath.row]
                return cell
            }
            
        }
        
    }
    
}
// MARK: UITableViewDelegate
extension CofirmOrder_Vc: UITableViewDelegate {
    /// 点击行事件
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath){
        tableView.deselectRow(at: indexPath, animated: true)
        let model = self.orderFormModel!
        if model.issueaninvoice == "1" || model.myvoucherlist.count > 0 {
            /// 显示发票选项
            if indexPath.section == model.effective.count {
                if indexPath.row == 0 && model.issueaninvoice == "1" {
                    self.performSegue(withIdentifier: "Invoice_Vc", sender: self.invoiceInf)
                }else{
                    /// 使用优惠券
                    self.performSegue(withIdentifier: "GwqList_Vc", sender: nil)
                }
            }else if indexPath.section == model.effective.count + 1 {
                
            }else{
                
            }
        }else{
            
        }
        
    }
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat{
        let model = self.orderFormModel!
        if model.issueaninvoice == "1" || model.myvoucherlist.count > 0 {
            /// 显示发票选项
            if indexPath.section == model.effective.count {
                return 47
            }else if indexPath.section == model.effective.count + 1 {
                /// 显示商品 金额总计
                /// 这块需要判断是否显示优惠券
                if self.voucherModel == nil {
                    return 85
                }else{
                    return 126
                }
            }else{
                let item  = model.effective[indexPath.section].array[indexPath.row]
                ///  1表示分割线 ,5 :tableview外层view 距离下面是5
                return CGFloat(85 * item.array.count) + 1 + 86 + 5
            }
        }else{
            /// 显示发票选项
            if indexPath.section == model.effective.count  {
                /// 显示商品 金额总计
                /// 这块需要判断是否显示优惠券
                if self.voucherModel == nil {
                    return 85
                }else{
                    return 126
                }
            }else{
                let item  = model.effective[indexPath.section].array[indexPath.row]
                ///  1表示分割线 ,5 :tableview外层view 距离下面是5
                return CGFloat(85 * item.array.count) + 1 + 86 + 5
            }
        }
    }
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat{
        let model = self.orderFormModel!
        if section < model.effective.count {
            return 40
        }else{
            return 0
        }
    }
    func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat{
        let model = self.orderFormModel!
        if section < model.effective.count {
            return 120
        }else{
            return 0
        }
    }
    ///自定义view
    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        let model = self.orderFormModel!
        if section < model.effective.count {
            /// 绘制 失效的 公司 header
            let cell = self.cofirmOrder_Tv.dequeueReusableCell(withIdentifier: "CofirmOrder_Hv") as! CofirmOrder_Hv
            let item  = model.effective[section]
            let relItem = (item,section)
            cell.item = relItem
            return cell
        }else{
            return nil
        }
    }
    func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView?{
        let model = self.orderFormModel!
        if section < model.effective.count {
            /// 绘制 失效的 公司 header
            let cell = self.cofirmOrder_Tv.dequeueReusableCell(withIdentifier: "CofirmOrder_Fv") as! CofirmOrder_Fv
            let item  = model.effective[section]
            cell.update_Closure = {
                self.updateOrderFormTvData()
            }
            cell.item = item
            return cell
        }else{
            return nil
        }
    }
    
}
